package com.frain.springcloud.common;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class RequestHelper {

    public static Map<String, Object> getParamMap(HttpServletRequest request) {

        Map<String, Object> map = new HashMap();

        try {
            Enumeration<String> enumeration = request.getParameterNames();
            while (enumeration.hasMoreElements()) {
                String name = enumeration.nextElement();
                map.put(name, request.getParameter(name));
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public static Map<String, String> getParamMapFromXml(HttpServletRequest request) {

        Map<String, String> map = new HashMap();

        try {

            ServletInputStream inputStream = request.getInputStream();

            SAXReader read = new SAXReader();
            Document document = read.read(inputStream);

            Element root = document.getRootElement();
            List<Element> elements = root.elements();

            for (Element element : elements) {
                map.put(element.getName(), element.getText());
            }

        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

}
